//
//  YTRegistVC.m
//  CllForIOS
//
//  Created by qiyun on 2018/3/9.
//  Copyright © 2018年 aRui. All rights reserved.
//

#import "YTRegistVC.h"
#import "AFHTTPSessionManager.h"
#import "YTLoginVC.h"

@interface YTRegistVC ()<UIScrollViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITextField * phonef;
@property (nonatomic, strong) UITextField * checkcodef;
@property (nonatomic, strong) UITextField * codef;
@property (nonatomic, strong) UITextField * againcodef;
@property (nonatomic, strong) UITextField * invitecodef;

@property (nonatomic, strong) NSString * imageCode;
@property (nonatomic, strong) NSString * checkCode;
@end

@implementation YTRegistVC
- (BOOL)prefersStatusBarHidden {
    return YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView*bg=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
    bg.image=IMAGE(@"Loginbg");
    [self.view addSubview:bg];
    //
    UIScrollView*scrollview=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
    scrollview.contentSize=CGSizeMake(SCREEN_W, SCREEN_H+1);
    scrollview.delegate=self;
    scrollview.showsVerticalScrollIndicator=NO;
    [self.view addSubview:scrollview];
    //
    UIImageView*title=[[UIImageView alloc]initWithFrame:CGRectMake(100,k_statusbarHeight+AfW(96), AfW(91), AfW(22))];
    title.image=IMAGE(@"registtitle");
    CGPoint titlecenter=title.center;
    titlecenter.x=SCREEN_W/2;
    title.center=titlecenter;
    [scrollview addSubview:title];
    //
    UIImageView*phonebg=[[UIImageView alloc]initWithImage:IMAGE(@"loginphonebg")];
    [scrollview addSubview:phonebg];
    UITextField*phonef=[[UITextField alloc]init];
    phonef.delegate=self;
    [self setTextfiled:phonef withPlaceholderstr:@"请您输入手机号码"];
    [scrollview addSubview:phonef];
    self.phonef=phonef;
    
    UIImageView*checkcodebg=[[UIImageView alloc]initWithImage:IMAGE(@"logincheckbg")];
    [scrollview addSubview:checkcodebg];
    UITextField*checkcodef=[[UITextField alloc]init];
    checkcodef.delegate=self;
    [self setTextfiled:checkcodef withPlaceholderstr:@"请您输入验证码"];
    [scrollview addSubview:checkcodef];
    self.checkcodef=checkcodef;
    
    
    UIImageView*codebg=[[UIImageView alloc]initWithImage:IMAGE(@"loginphonebg")];
    [scrollview addSubview:codebg];
    UITextField*codef=[[UITextField alloc]init];
    codef.delegate=self;
    [self setTextfiled:codef withPlaceholderstr:@"请您输入密码"];
    codef.secureTextEntry = YES;
    [scrollview addSubview:codef];
    self.codef=codef;
    
    UIImageView*againcodebg=[[UIImageView alloc]initWithImage:IMAGE(@"logincodebg")];
    [scrollview addSubview:againcodebg];
    UITextField*againcodef=[[UITextField alloc]init];
    againcodef.delegate=self;
    [self setTextfiled:againcodef withPlaceholderstr:@"请再次确认密码"];
    againcodef.secureTextEntry = YES;
    [scrollview addSubview:againcodef];
    self.againcodef=againcodef;
    
    UIImageView*invitecodebg=[[UIImageView alloc]initWithImage:IMAGE(@"logincodebg")];
    [scrollview addSubview:invitecodebg];
    UITextField*invitecodef=[[UITextField alloc]init];
    invitecodef.delegate=self;
    [self setTextfiled:invitecodef withPlaceholderstr:@"请输入邀请码"];
    [scrollview addSubview:invitecodef];
    self.invitecodef=invitecodef;
    
    
    phonebg.frame=CGRectMake(47, CGRectGetMaxY(title.frame)+36, SCREEN_W-47*2, 44);
    checkcodebg.frame=CGRectMake(47, CGRectGetMaxY(phonebg.frame)+22, SCREEN_W-47*2, 44);
    codebg.frame=CGRectMake(47, CGRectGetMaxY(checkcodebg.frame)+22, SCREEN_W-47*2, 44);
    againcodebg.frame=CGRectMake(47, CGRectGetMaxY(codebg.frame)+22, SCREEN_W-47*2, 44);
    invitecodebg.frame=CGRectMake(47, CGRectGetMaxY(againcodebg.frame)+22, SCREEN_W-47*2, 44);
    
    phonef.frame=CGRectMake(47+43, 20, SCREEN_W-47*2-43, 17);
    CGPoint phonefcenter=phonef.center;
    phonefcenter.y=phonebg.center.y;
    phonef.center=phonefcenter;

    checkcodef.frame=CGRectMake(47+43, 20, SCREEN_W-47*2-43-110-9, 17);
    CGPoint checkcodefcenter=checkcodef.center;
    checkcodefcenter.y=checkcodebg.center.y;
    checkcodef.center=checkcodefcenter;

    codef.frame=CGRectMake(47+43, 20, SCREEN_W-47*2-43, 17);
    CGPoint codefcenter=codef.center;
    codefcenter.y=codebg.center.y+2;
    codef.center=codefcenter;

    againcodef.frame=CGRectMake(47+43, 20, SCREEN_W-47*2-43, 17);
    CGPoint againcodefcenter=againcodef.center;
    againcodefcenter.y=againcodebg.center.y+2;
    againcodef.center=againcodefcenter;

    invitecodef.frame=CGRectMake(47+43, 20, SCREEN_W-47*2-43, 17);
    CGPoint invitecodefcenter=invitecodef.center;
    invitecodefcenter.y=invitecodebg.center.y+2;
    invitecodef.center=invitecodefcenter;

    

    //
    UIButton*toLoginBtn=[[UIButton alloc]init];
    toLoginBtn.titleLabel.font=KFONT(12);
    [toLoginBtn setTitle:@"已有账号?点此登录" forState:UIControlStateNormal];
    [toLoginBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [toLoginBtn setTitleColor:RGBA(215, 217, 221) forState:UIControlStateNormal];
    [scrollview addSubview:toLoginBtn];
    [toLoginBtn addTarget:self action:@selector(jumpToLogin) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton*getCheckCodeBtn=[[UIButton alloc]init];
    getCheckCodeBtn.titleLabel.font=KFONT(12);
    [getCheckCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [getCheckCodeBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [getCheckCodeBtn setTitleColor:RGBA(215, 217, 221) forState:UIControlStateNormal];
    [getCheckCodeBtn addTarget:self action:@selector(toGetCheckCode:) forControlEvents:UIControlEventTouchUpInside];

    [getCheckCodeBtn setBackgroundImage:IMAGE(@"chcekcodebg") forState:UIControlStateNormal];
    [scrollview addSubview:getCheckCodeBtn];
    
    UIButton*RegisterBtn=[[UIButton alloc]init];
    RegisterBtn.titleLabel.font=KFONT_bold(15);
    [RegisterBtn setBackgroundImage:IMAGE(@"loginBtnbg") forState:UIControlStateNormal];
    [RegisterBtn setTitle:@"注册" forState:UIControlStateNormal];
    [scrollview addSubview:RegisterBtn];
    [RegisterBtn addTarget:self action:@selector(toRegister) forControlEvents:UIControlEventTouchUpInside];
    toLoginBtn.frame=CGRectMake(56, CGRectGetMaxY(invitecodebg.frame)+17, 120, 12);
    
    getCheckCodeBtn.frame=CGRectMake(CGRectGetMaxX(checkcodebg.frame)-9-110, CGRectGetMaxY(phonebg.frame)+31, 110, 27);
    CGPoint  getCheckCodeBtncenter=getCheckCodeBtn.center;
    getCheckCodeBtncenter.y=checkcodebg.center.y;
    getCheckCodeBtn.center=getCheckCodeBtncenter;
    
    
    RegisterBtn.frame=CGRectMake(47, CGRectGetMaxY(toLoginBtn.frame)+11, SCREEN_W-47*2, 44);
    
}
-(void)setTextfiled:(UITextField*)textfield withPlaceholderstr:(NSString*)str{
    
    
//    textfield.borderStyle = UITextBorderStyleRoundedRect;
    textfield.font = KFONT(12);
    textfield.textColor = RGBA(215, 217, 221);
    //光标颜色
    textfield.tintColor= RGBA(215, 217, 221);
    
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; // 创建属性字典
    attrs[NSFontAttributeName] =KFONT(12); // 设置font
    attrs[NSForegroundColorAttributeName] = RGBA(215, 217, 221); // 设置颜色
    NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:str attributes:attrs]; // 初始化富文本占位字符串
    textfield.attributedPlaceholder = attStr;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
#pragma  mark - 点击事件
-(void)jumpToLogin{
    
    [self.navigationController pushViewController:[YTLoginVC new] animated:1];
    
}
-(void)toRegister{
   //注册
    //判断手机号
    if (self.phonef.text.length <=0) {
        PROMPT(@"请输入手机号");
        return;
    }
    //判断验证码
    if (self.checkcodef.text.length <=0) {
        PROMPT(@"请输入验证码");
        return;
    }
    //判断密码
    if (self.codef.text.length <=0) {
        PROMPT(@"请输入密码");
        return;
    }
    //判断密码
    if (self.againcodef.text.length <=0) {
        PROMPT(@"请再次输入密码");
        return;
    }
    //判断密码相同
    if (self.codef.text!=self.againcodef.text) {
        PROMPT(@"两次密码不相同");
        return;
    }
    
    NSDictionary *dicts = @{@"mobile":_phonef.text,
                            @"msgCode":_checkcodef.text,
                            @"password":_codef.text,
                            @"passwordConfirm":_againcodef.text
                            };
    
    if (self.invitecodef.text.length>0) {
        dicts = @{@"mobile":_phonef.text,
                  @"msgCode":_checkcodef.text,
                  @"password":_codef.text,
                  @"passwordConfirm":_againcodef.text,
                  @"activeCode":_invitecodef.text
                  };
    }
    __weak typeof(self) weakSelf = self;
    [SendRequest getinfoDetailWithURL:k_MainUrl(k_User_register) withDictionary:dicts result:^(NSDictionary *result, NSError *error) {
        NSLog(@"获取---%@",result);
        if ( [[result[@"code"] stringValue] isEqualToString:@"200"]) {
          [self.navigationController pushViewController:[YTLoginVC new]  animated:1];
        }else{
            PROMPT(result[@"message"]);
        }
    }];
    
    
}

-(void)toGetCheckCode:(UIButton*)sender{
    //判断手机号
    if (self.phonef.text.length <=0) {
        PROMPT(@"请输入手机号");
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary *dicts = @{@"mobile":_phonef.text};
    __weak typeof(self) weakSelf = self;
    [SendRequest getinfoDetailWithURL:k_MainUrl(k_User_checkNum) withDictionary:dicts result:^(NSDictionary *result, NSError *error) {
        NSLog(@"获取---%@",result);
        if ( [[result[@"code"] stringValue] isEqualToString:@"200"]) {
          [self imageVerifyCode];
            
            __block int timeout = 60;  //倒计时时间
            dispatch_queue_t queue = dispatch_get_main_queue();
            
            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
            
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout <= 0)
                {
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        sender.enabled = YES;
                        sender.userInteractionEnabled = YES;
                        [sender setTitle:@"重新获取" forState:UIControlStateNormal];
                        dispatch_suspend(_timer);
                        
                    });
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        sender.enabled = YES;
                        sender.userInteractionEnabled = NO;
                        [sender setTitle:[NSString stringWithFormat:@"剩余%d秒", timeout]forState:UIControlStateNormal];
                        //sender.titleLabel.font = NUMBER(12);
                        [sender setTitleColor:RGBA(215, 217, 221) forState:UIControlStateNormal];
                        
                    });
                    timeout--;
                }
            });
            
            dispatch_resume(_timer);
            
        }else{
            PROMPT(result[@"message"]);
        }
         [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
    
}
//弄图形验证码
-(void)imageVerifyCode{
    
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:k_MainUrl(k_User_generateCheckCode) parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // task 我们可以通过task拿到响应头
        // responseObject:请求成功返回的响应结果（AFN内部已经把响应体转换为OC对象，通常是字典或数组)
        
        NSString*base64str=[NSString stringWithFormat:@"%@",(NSDictionary*)responseObject[@"imageString"]];
        NSData * imageData =[[NSData alloc] initWithBase64EncodedString:base64str options:NSDataBase64DecodingIgnoreUnknownCharacters];
        UIImage *image = [UIImage imageWithData:imageData ];
        
       //带输入框的弹框
        [self showalert:image];
    
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // error 错误信息
        NSLog(@"%@",error);
    }];
  

}

-(void)showalert:(UIImage*)image{
    //提示框添加文本输入框
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:@""
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * action) {
                                                         //响应事件
                                                         for(UITextField *text in alert.textFields){
                                                             NSLog(@"text = %@", text.text);
                                                             self.imageCode=text.text;
                                                             
                                                         }
                                                         
                                                         
                                                         
                                                         if (self.imageCode) {
                                                             NSDictionary *dicts = @{@"code":self.imageCode,
                                                                                     @"mobile":_phonef.text,
                                                                                     
                                                                                     @"type":@2
                                                                                     };
                                                             __weak typeof(self) weakSelf = self;
                                                             [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                                                             [SendRequest getinfoDetailWithURL:k_MainUrl(k_User_getMsgCode) withDictionary:dicts result:^(NSDictionary *result, NSError *error) {
                                                                 NSLog(@"获取---%@",result);
                                                                 if ( [[result[@"code"] stringValue] isEqualToString:@"200"]) {
                                                                     self.checkCode=result[@"sRand"];
                                                                 }else{
                                                                     PROMPT(result[@"message"]);
                                                                 }
                                                                  [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                                             }];
                                                         }
                                                         
                                                         
                                                         
                                                     }]; 
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                             NSLog(@"action = %@", alert.textFields);
                                                         }];
    UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, 70, 30)];
    CGPoint centerimageView2=imageView2.center;
    centerimageView2.x=270/2;
    imageView2.center=centerimageView2;
    
    imageView2.image =image;
    [alert.view addSubview:imageView2];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"";
       
    }];
    
    [alert addAction:okAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
